package gl;

import gl.android.biyiqing.R;
import gl.common.DataLoadFail;
import gl.common.DataLoadSuccess;
import gl.common.DataLoading;
import gl.layout.swipeback.SwipeBackActivity;
import gl.layout.swipeback.SwipeBackLayout;
import gl.toast.OnClickWrapper;
import gl.toast.OnDismissWrapper;
import gl.toast.SuperCardToast;
import gl.toast.SuperToast;
import gl.uitls.Lg;
import gl.uitls.Tip;
import net.tsz.afinal.FinalDb;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;

public class BaseActivity extends SwipeBackActivity {

	private static final String DATABASE_NAME = "cricle";
	public FinalDb mFinalDb;
	public final String TAG = getClass().getSimpleName();
	private SuperCardToast superCardToastProgress;
	private SuperCardToast superCardToastTryAgain;

	public void postRunnableDelayOnUIThread(Runnable mRunnable) {
		new Handler().postDelayed(mRunnable,
				getResources()
						.getInteger(android.R.integer.config_longAnimTime));
	}

	public void postRunnableDelayOnUIThread(Runnable mRunnable, long delay) {
		new Handler().postDelayed(mRunnable, delay);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setSwipeBackEnable(false);
		getSwipeBackLayout().setEdgeTrackingEnabled(SwipeBackLayout.EDGE_RIGHT);
		mFinalDb = FinalDb.create(this, DATABASE_NAME);
		App.getApp().addActivity(this);
		hideSoftInput();
		IntentFilter filter = new IntentFilter(
				ConnectivityManager.CONNECTIVITY_ACTION);
		this.registerReceiver(networkBroadcast, filter);
		EventBus.getDefault().register(this);

		superCardToastProgress = new SuperCardToast(this,
				SuperToast.Type.PROGRESS);
		superCardToastProgress.setAnimations(SuperToast.Animations.FADE);
		superCardToastProgress.setIndeterminate(true);
		superCardToastProgress.show();

		superCardToastTryAgain = new SuperCardToast(this,
				SuperToast.Type.BUTTON);
		superCardToastTryAgain.setText("click to retry");
		superCardToastTryAgain.setAnimations(SuperToast.Animations.FADE);
		superCardToastTryAgain.setOnClickWrapper(onClickWrapper);
		superCardToastTryAgain.show();
	}

	private void hideSoftInput() {
		int inputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
		inputMode = inputMode
				| WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN;
		getWindow().setSoftInputMode(inputMode);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
	}

	@Override
	protected void onStart() {
		super.onStart();
		EasyTracker.getInstance(this).activityStart(this);
	}

	@Override
	protected void onStop() {
		super.onStop();
		EasyTracker.getInstance(this).activityStop(this);
	}

	@Override
	public void finish() {
		super.finish();
	}

	public void onEvent(DataLoading mDataLoading) {
		Lg.i("DataLoading");
		superCardToastProgress.show();
	}

	public void onEvent(DataLoadSuccess mDataLoading) {
		Lg.i("DataLoadSuccess");
		// superCardToastProgress.dismiss();
	}

	public void onEvent(DataLoadFail mDataLoading) {
		Lg.i("DataLoadFail");
		superCardToastProgress.dismiss();
		superCardToastTryAgain.show();
	}

	@Override
	protected void onDestroy() {
		EventBus.getDefault().unregister(this);
		this.unregisterReceiver(networkBroadcast);
		super.onDestroy();

	}

	@Override
	public void startActivity(Intent intent) {
		System.err.println("startActivity");
		super.startActivity(intent);
		overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);

	}

	public void showErr(String err) {
		final TextView tv = (TextView) findViewById(android.R.id.text1);
		if (null != tv) {
			(tv).setText(err);
			(tv).setVisibility(View.VISIBLE);
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					tv.setVisibility(View.GONE);
				}
			}, 3000);
		}
	}

	public void showErrWithTry(String err, View.OnClickListener mOnClickListener) {
		TextView tv = (TextView) findViewById(android.R.id.text1);
		if (null != tv) {
			(tv).setText(err);
			(tv).setVisibility(View.VISIBLE);
			(tv).setOnClickListener(mOnClickListener);
		}
	}

	void showDialog(String message) {
		dismissDialog();
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage(message);
		builder.setTitle("提醒");
		builder.setPositiveButton("取消", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.setNegativeButton("设置", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.HONEYCOMB) {
					Intent intent = new Intent(
							android.provider.Settings.ACTION_SETTINGS);
					startActivityForResult(intent, 0);
				} else {
					Intent intent = new Intent();
					ComponentName component = new ComponentName(
							"com.android.settings",
							"com.android.settings.WirelessSettings");
					intent.setComponent(component);
					intent.setAction("android.intent.action.VIEW");
					startActivityForResult(intent, 0);
				}
			}
		});
		mAlertDialog = builder.create();
		mAlertDialog.show();
	}

	boolean isCanExit = false;

	public void exitPressAgain() {
		if (!isCanExit) {
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					isCanExit = false;
				}
			}, 3000);
			isCanExit = true;
			Tip.show("再按一次退出");
		} else {
			finish();
		}

	}

	private void dismissDialog() {
		if (mAlertDialog != null && mAlertDialog.isShowing()) {
			mAlertDialog.dismiss();
		}
	}

	AlertDialog mAlertDialog;
	private BroadcastReceiver networkBroadcast = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			State wifiState = null;
			State mobileState = null;
			ConnectivityManager cm = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
					.getState();
			if (cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null) {
				mobileState = cm
						.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
						.getState();
			}

			if (wifiState != null && mobileState != null
					&& State.CONNECTED != wifiState
					&& State.CONNECTED == mobileState) {
				Log.e(TAG, "on mobile~~~");
				dismissDialog();
			} else if (wifiState != null && mobileState != null
					&& State.CONNECTED != wifiState
					&& State.CONNECTED != mobileState) {
				Log.e(TAG, "disconnect network~~~");
				showDialog("网络异常,请重新设置网络~~~");
			} else if (wifiState != null && State.CONNECTED == wifiState) {
				Log.e(TAG, "on wifi~~~");
				dismissDialog();
			}
		}

	};
	private OnClickWrapper onClickWrapper = new OnClickWrapper(
			"onclickwrapper_one", new SuperToast.OnClickListener() {

				@Override
				public void onClick(View v, Parcelable token) {

					SuperToast superToast = new SuperToast(v.getContext());
					superToast.setText("onClick!");
					superToast.setDuration(SuperToast.Duration.VERY_SHORT);
					superToast.setBackground(SuperToast.Background.BLUE);
					superToast.setTextColor(Color.WHITE);
					superToast.show();

				}

			});

	protected OnDismissWrapper onDismissWrapper = new OnDismissWrapper(
			"ondismisswrapper_one", new SuperToast.OnDismissListener() {

				@Override
				public void onDismiss(View view) {

					SuperToast superToast = new SuperToast(view.getContext());
					superToast.setText("onDismiss!");
					superToast.setDuration(SuperToast.Duration.VERY_SHORT);
					superToast.setBackground(SuperToast.Background.RED);
					superToast.setTextColor(Color.WHITE);
					superToast.show();

				}
			});

}
